#include "clock.h"
#include "modbus.h"

type_clock clock_data;

void clock_init(void)
{
}

uint8_t clock_wait_even(I2C_Event_TypeDef even)
{
  uint8_t t=0;
  for(t=0;t<CLOCK_TIMEOUT&&!I2C_CheckEvent(even);t++);
  return t==CLOCK_TIMEOUT ? 1 : 0;
}

uint8_t clock_wait_flag(I2C_Flag_TypeDef flag)
{
  uint8_t t=0;
  for(t=0;t<CLOCK_TIMEOUT&&I2C_GetFlagStatus(flag);t++);
  return t==CLOCK_TIMEOUT ? 1 : 0;
}

uint8_t clock_write(uint8_t addr, uint8_t* data, uint8_t len)
{
  if(clock_wait_flag(I2C_FLAG_BUSBUSY)) return 1;
  I2C_GenerateSTART(ENABLE);
  if(clock_wait_even(I2C_EVENT_MASTER_MODE_SELECT)) return 2;
  I2C_Send7bitAddress(CLOCK_ADDR, I2C_DIRECTION_TX);
  if(clock_wait_even(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) return 3;
  I2C_SendData(addr);
  while(len--)
  {
    if(clock_wait_even(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) return 4;
    I2C_SendData(*data++);
  }
  if(clock_wait_even(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) return 5;
  I2C_GenerateSTOP(ENABLE);
  return 0;
}

uint8_t clock_err;

uint8_t clock_read(uint8_t addr, uint8_t *data, uint8_t len)
{
  if(clock_wait_flag(I2C_FLAG_BUSBUSY)) return 1;
  I2C_GenerateSTART(ENABLE);
  if(clock_wait_even(I2C_EVENT_MASTER_MODE_SELECT)) return 2;
  I2C_Send7bitAddress(CLOCK_ADDR, I2C_DIRECTION_TX);
  if(clock_wait_even(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) return 3;
  I2C_SendData(addr);
  if(clock_wait_even(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) return 4;
  I2C_GenerateSTART(ENABLE);
  if(clock_wait_even(I2C_EVENT_MASTER_MODE_SELECT)) return 5;
  I2C_Send7bitAddress(CLOCK_ADDR, I2C_DIRECTION_RX);
  if(clock_wait_even(I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)) return 6;
  while(len--)
  {
    if(clock_wait_even(I2C_EVENT_MASTER_BYTE_RECEIVED)) return 7;
    *data = I2C_ReceiveData();
    data++;
  } 
  I2C_GenerateSTOP(ENABLE);
  return 0;
}

uint8_t temp[16]={0x00};

void clock_get(uint8_t *data)
{
  assert_param(clock_read(0x00, data, 6) == 0);
}

void clock_set(uint8_t addr, uint8_t* data, uint8_t len)
{
  assert_param(clock_write(addr, data, len) == 0);
}

void clock_modbus_read(uint16_t addr, uint8_t len)
{
  addr &= 0x0fff;
  if(addr > 5)
  {
    modbus_err(3, 2);
    return;
  }
  if(addr+len>6)
  {
    modbus_err(3, 3);
    return;
  }
  uint8_t data[8];
  clock_get(data);
  uint8_t *pc = modbus_txpc();	
  *(pc+1) = 0x03;
  *(pc+2) = len<<1;
  for(uint8_t i=0;i<len;i++)
  {
    *(pc+3+i*2) = 0;
    *(pc+4+i*2) = data[addr+i];
  }
  modbus_write(pc, 3+len*2);
}

void clock_modbus_write(uint8_t *pc)
{
  
}

void clock_modbus(uint8_t *pc)
{
  type_s2c *data = (type_s2c *)(pc+1);
  switch(*pc)
  {
  case 0x03: clock_modbus_read(data->s, *(pc+4));       break;
  default: modbus_err(*pc, 1);
  }
}

void clock_timer(void)
{  
  
}
